package Link;

import java.util.Stack;

public class BM13 {
    public class ListNode {
        int val;
        ListNode next = null;
        public ListNode(int val) {
            this.val = val;
        }
    }
    //判断一个链表是否为回文结构
    public boolean isPail (ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode temp = head;
        Stack<Integer> stack = new Stack<>();

        while (temp != null) {
            stack.push(temp.val);
            temp = temp.next;
        }

        while (!stack.isEmpty()) {
            if (stack.pop() != head.val) {
                return false;
            }
            head = head.next;
        }
        return true;
    }

    //优化
    public boolean isPail01 (ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode temp = head;
        Stack<Integer> stack = new Stack<>();
        int len = 0;

        while (temp != null) {
            stack.push(temp.val);
            temp = temp.next;
            len++;
        }
        //len 长度除以2
        len >>= 1;

        while (len-- >= 0) {
            if (stack.pop() != head.val) {
                return false;
            }
            head = head.next;
        }
        return true;
    }
}
